<template>
  <div>
    <el-page-header @back="goBack" :content=courseForm.courseTitle>

    </el-page-header>

    <div style="text-align:left;margin-top:40px;width:100%;min-height:300px">
      <div style="float:left;margin-left:20px">
        <img :src="`http://101.43.223.224:8765/image/getImageById?id=${courseForm.courseImg}`" style="height:180px">
      </div>
      <div style="float:left;margin-left:5%;width:70%;font-size:16px;color:#909399">
        <div style="height:40px">
          <div style="letter-spacing: 1px;">课程标题:&nbsp;<span style="color:#606266">{{courseForm.courseTitle}}</span></div>

        </div>

        <div style="height:40px">
          <div style="width:140px;float:left;letter-spacing: 1px;">教师:&nbsp;<span style="color:#606266">{{courseForm.teacherName}}</span></div>
          <div style="width:240px;float:left;letter-spacing: 1px;">科目:&nbsp;<span style="color:#606266">{{courseForm.dictName}}</span></div>
        </div>

        <div style="height:40px">
          <div style="width:140px;float:left;letter-spacing: 1px;" v-if="courseForm.payType==0">是否付费:&nbsp;<span style="color:#606266">免费</span></div>
          <div style="width:140px;float:left;letter-spacing: 1px;" v-if="courseForm.payType==1">是否付费:&nbsp;<span style="color:#606266">付费</span></div>
          <div style="width:240px;float:left;letter-spacing: 1px;" v-if="courseForm.payType==1">价钱:&nbsp;<span style="color:#606266">￥{{courseForm.coursePrice}}</span></div>
        </div>

        <div style="height:40px">
          <div style="width:140px;float:left;letter-spacing: 1px;">
            状态:&nbsp;<el-tag type="success" v-if="courseForm.courseStatus == 0" color="#19caad;">已上架</el-tag>
            <el-tag type="danger" v-if="courseForm.courseStatus == 1">未上架</el-tag>
          </div>
          <div style="float:left;letter-spacing: 1px;" v-if="courseForm.courseStatus==0">上架时间:&nbsp;<span style="color:#606266">{{courseForm.upTime}}</span></div>
        </div>

        <div style="height:40px">
          <div style="letter-spacing: 1px;">介绍:&nbsp;<span style="color:#606266">{{courseForm.courseInfo}}</span></div>
        </div>
      </div>

    </div>

    <el-row>
      <el-col :span="4">
        <el-button @click="openUnitAdd()" type="primary" plain style="margin-left:10px">添加章节</el-button>
      </el-col>
    </el-row>
    <div style="background:#fff;width:100%;height:100%;margin-top:10px">
      <el-table :data="unitData" style="width: 100%; margin-top: 10px; margin-left: 15px" :header-cell-class-name="'headerBg'">
        <el-table-column width="55"></el-table-column>
        <el-table-column prop="serialNumber" label="序号" align="center" width="55">
        </el-table-column>
        <el-table-column prop="unitTitle" label="章节标题" align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="unitInfo" label="章节介绍" align="center" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="unitStatus" label="章节状态" align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.unitStatus" active-color="#13ce66" inactive-color="#ff4949" :active-value="0" :inactive-value="1" @change=changliveRoomStatus($event,scope.row)>
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" align="center">
          <template slot-scope="scope">
            <!-- <el-button type="primary" size="small" style="background:none;border:0px"><span style="color:#409EFF;" @click="FileManagerUpdateWindows(scope.row)">添加视频</span></el-button> -->
            <el-button type="primary" size="small" slot="reference" style="background:none;border:0px"><span style="color:#409EFF;" @click="openUnitUpdate(scope.row)">修改</span></el-button>
            <el-button type="primary" size="small" slot="reference" style="background:none;border:0px"><span style="color:#409EFF;" @click="delUnit(scope.row.id)">删除</span></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog :visible.sync="addButton" width="30%" style="text-align: left">
      <div slot="title" class="header-title" style="text-align: left;font-weight: bold;color: white;font-size: 18px;margin-bottom: 10px;">
        添加章节信息
      </div>
      <el-form stripe style="width: 100%; text-align: left" :model="unitForm" ref="unitForm" :rules="rules">
        <el-form-item width="100%" prop="unitTitle">
          <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
          <span style="margin-left: 20px">章节标题</span>
          <el-input style="width: 80%; margin-left: 20px" v-model="unitForm.unitTitle" placeholder="请输入章节标题" :maxlength="20" show-word-limit clearable></el-input>
        </el-form-item>
        <el-form-item width="100%" prop="unitInfo">
          <span style="font-weight: 900; color: rgb(93, 142, 255)">|</span>
          <span style="margin-left: 20px">章节介绍</span>
          <el-input style="width: 80%; margin-left: 20px" v-model="unitForm.unitInfo" type="textarea" placeholder="请输入章节介绍" :maxlength="200" show-word-limit clearable></el-input>
        </el-form-item>
        
        <el-form-item width="100%" prop="unitInfo">
          <uploader style="margin-left: 20px" :autoStart="false" :options="options" :file-status-text="statusText" class="uploader-example" @file-complete="fileComplete" @complete="complete" @file-success="fileSuccess"
          @files-added="filesAdded">
            <uploader-btn style="border: 1px solid rgb(200, 200, 230);border-radius: 4px;">点击添加课程视频</uploader-btn>
        </uploader>
        </el-form-item>
      </el-form>
      <el-button style="background-color: rgb(234, 244, 255); color: rgb(96, 169, 255)" @click="addUnit()">确 定</el-button>
      <el-button @click="addButton = false" style="background-color: rgb(234, 244, 255); color: rgb(96, 169, 255)">取 消</el-button>
    </el-dialog>

      <!-- 章节内添加视频（马佳乐） -->
      <el-dialog :visible.sync="fileupdate" width="30%" style="text-align: left">
        <div slot="title" class="header-title" style="text-align: left;font-weight: bold;color: white;font-size: 18px;margin-bottom: 10px;">
          分配视频
        </div>
        <el-form stripe style="width: 100%; text-align: left" :model="fileForm" ref="fileForm">
          <el-form-item  label="分配视频">
            <el-select clearable v-model="fileForm.fileId" placeholder="请选择视频">
              <el-option
                  v-for="item in fileType"
                  :key="item.fileManagerId"
                  :label="item.fileManagerName"
                  :value="item.fileManagerId+''">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <el-button style="background-color: rgb(234, 244, 255); color: rgb(96, 169, 255)" @click="FileManagerUpdate('')">确 定</el-button>
        <el-button @click="addButton = false" style="background-color: rgb(234, 244, 255); color: rgb(96, 169, 255)">取 消</el-button>
      </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import SparkMD5 from "spark-md5";
export default {
  components: {},
  data() {
    return {
      fileUploaded: false, // 添加一个标志变量用于追踪文件上传状态
      user: JSON.parse(localStorage.getItem("user")),
      fileList: [],
      options: {
        target: `${axios.defaults.baseURL}/upload/chunk`,
        // 开启服务端分片校验功能
        testChunks: true,
        parseTimeRemaining: function (timeRemaining, parsedTimeRemaining) {
          return parsedTimeRemaining
            .replace(/\syears?/, "年")
            .replace(/\days?/, "天")
            .replace(/\shours?/, "小时")
            .replace(/\sminutes?/, "分钟")
            .replace(/\sseconds?/, "秒");
        },
        // 服务器分片校验函数
        checkChunkUploadedByResponse: (chunk, message) => {
          const result = JSON.parse(message);
          if (result.data.skipUpload) {
            this.skip = true;
            return true;
          }
          return (result.data.uploaded || []).indexOf(chunk.offset + 1) >= 0;
        },
        // headers: {
        //     // 在header中添加的验证，请根据实际业务来
        //     "Access-Token": storage.get(ACCESS_TOKEN),
        // },
      },
      statusText: {
        success: "上传成功",
        error: "上传出错了",
        uploading: "上传中...",
        paused: "暂停中...",
        waiting: "等待中...",
        cmd5: "计算文件MD5中...",
      },
      //课程表单
      courseForm: {},
      //章节表单
      unitForm: {},
      //课程id
      courseId: 0,
      addButton: false,
      //章节数组
      unitData: [],
      // 章节内添加视频数据
      fileForm: {},
      // 点开页面时添加视频页面处于关闭状态
      fileupdate: false,
      // 添加视频数据
      fileType: {},
      // 验证
      rules: {
        unitTitle: [
          {
            required: true,
            message: "请输入标题",
            trigger: "blur",
          },
        ],
        unitInfo: [
          {
            required: true,
            message: "请输入介绍",
            trigger: "blur",
          },
        ],
      },
    };
  },
  mounted() {
    // 在目标页面获取id参数
    this.courseId = this.$route.params.id;
    this.selectUnit();
    this.selectCourse();
    // 章节内视频查看（马佳乐）
    this.getfile();
  },
  methods: {
    changliveRoomStatus(e, data) {
      // console.log(id)
      if (data.unitStatus == 1) {
        this.banneds(data.id);
      } else {
        this.enables(data.id);
      }
    },
    // 将章节进行下架
    banneds(id) {
      const form = new FormData();
      form.set("id", id);
      this.$axios
        .post("/course_unit/banned", form)
        .then((res) => {
          if (res.data.code == 200) {
            this.Mymessage("success", "下架成功");
            this.updatedisable = false;
            this.selectUnit();
          } else {
            this.Mymessage("wanging", "下架失败");
          }
        })
        .catch(() => {
          this.Mymessage("info", "下架有误");
        });
    },
    // 将章节上架的方法
    enables(id) {
      const forms = new FormData();
      forms.set("id", id);
      this.$axios
        .post("/course_unit/enables", forms)
        .then((res) => {
          if (res.data.code == 200) {
            this.Mymessage("success", "上架成功");
            this.selectUnit();
          } else {
            this.Mymessage("wanging", "上架失败");
          }
        })
        .catch(() => {
          this.Mymessage("info", "上架有误");
        });
    },
    // 打开添加弹窗
    openUnitAdd() {
      this.addButton = true;
      this.unitForm.teacherId = JSON.parse(localStorage.getItem("user")).id;
      this.unitForm.courseId = this.courseId;
    },
    // 打开修改弹窗
    openUnitUpdate(row) {
      this.selectUnitById(row);

      this.addButton = true;
    },
    // 修改状态
    // upSwitch(row){
    //   this.$axios.get("/course_unit/upSwitch",{
    //       params: {
    //         id:row.id,
    //         unitStatus:row.unitStatus
    //         }})
    //   .then((res) => {
    //     if((res.data.code==200)){
    //       this.selectUnit()
    //     }
    //   })
    // },
    // 删除
    delUnit(id) {
      this.$axios
        .get("/course_unit/delUnit", {
          params: {
            id: id,
          },
        })
        .then((res) => {
          if (res.data.code == 200) {
            this.selectUnit();
            this.$message.success("删除成功!!");
          }
        });
    },
    // 禁用
    jinyong(id) {
      this.$axios
        .get("/course_unit/disUnit", {
          params: {
            id: id,
          },
        })
        .then((res) => {
          if (res.data.code == 200) {
            this.selectUnit();
          }
        });
    },
    // 启用
    qiyong(id) {
      this.$axios
        .get("/course_unit/enableUnit", {
          params: {
            id: id,
          },
        })
        .then((res) => {
          if (res.data.code == 200) {
            this.selectUnit();
          }
        });
    },
    // 返回课程
    goBack() {
      this.$router.push("/course");
    },
    selectUnitById(row) {
      this.$axios
        .get("/course_unit/selectUnitById", {
          params: {
            id: row.id,
          },
        })
        .then((res) => {
          if ((res.code = 200)) {
            this.unitForm = res.data.data;
            this.unitForm.teacherId = JSON.parse(
              localStorage.getItem("user")
            ).id;
          }
        })
        .catch((err) => {});
    },
    selectCourse() {
      this.$axios
        .get("/back_course/selectCourseById", {
          params: {
            id: this.courseId,
          },
        })
        .then((res) => {
          if ((res.code = 200)) {
            this.courseForm = res.data.data;
          }
        })
        .catch((err) => {});
    },
    addUnit() {
      if(!this.unitForm.id){
        if (!this.fileUploaded) {
        this.$message.error("请添加视频!!!");
        return;
      }
      if (!this.unitForm.fileId) {
        this.$message.error("视频信息有误或视频已存在，请重新上传!!!");
        return;
      }
    }
      
      this.$refs["unitForm"].validate((valid) => {
        if (valid) {
          // if
          if (this.unitForm.id == undefined) {
            this.$axios
              .post("/course_unit/addUnit", this.unitForm)
              .then((res) => {
                if ((res.data.code = 200)) {
                  this.$message.success("添加成功!!");
                  this.addButton = false;
                  this.unitForm = {};
                  this.selectUnit();
                }
              })
              .catch((err) => {});
          } else {
            this.$axios
              .post("/course_unit/updateUnit", this.unitForm)
              .then((res) => {
                if ((res.data.code = 200)) {
                  this.$message.success("修改成功!!");
                  this.addButton = false;
                  this.unitForm = {};
                  this.selectUnit();
                }
              })
              .catch((err) => {});
          }
        } else {
          this.$message.error("error submit!!");
        }
      });
    },
    //根据课程全查章节
    selectUnit() {
      this.$axios
        .get("/course_unit/selectUnit", {
          params: {
            courseId: this.courseId,
          },
        })
        .then((res) => {
          if ((res.data.code = 200)) {
            this.unitData = res.data.data.content.map((item, index) => {
              return {
                ...item,
                serialNumber: index + 1,
              };
            });
          }
        })
        .catch((err) => {});
    },
    // 章节内视频全查（马佳乐）
    getfile() {
      this.$axios
        .get("/course_unit/selectFile", {
          params: {
            fileType: ".mp4",
          },
        })
        .then((res) => {
          if (res.data.flag) {
            this.fileType = res.data.data;
          }
        })
        .catch((err) => {
          this.Mymessage(err, "获取失败");
        });
    },
    // 章节内添加视频
    FileManagerUpdate() {
      // 手动提交表单
      this.$axios
        .post("/course_unit/addFile", this.fileForm)
        .then((res) => {
          if (res.data.flag) {
            this.Mymessage("success", res.data.data);
            this.fileupdate = false;
            this.selectUnit();
          } else {
            this.Mymessage("waning", res.data.data);
          }
        })
        .catch((err) => {});
    },
    // 章节内添加视频方法（马佳乐）
    FileManagerUpdateWindows(data) {
      this.fileForm = JSON.parse(JSON.stringify(data));
      this.fileupdate = true;
    },
    // 弹窗提示
    Mymessage(type, text) {
      this.$message({
        showClose: true,
        message: text,
        type: type,
      });
    },
    fileComplete(rootFile) {
      // 一个根文件（文件夹）成功上传完成。
      // console.log("fileComplete", rootFile);
      // console.log("一个根文件（文件夹）成功上传完成。");
    },
    complete() {
      // 上传完毕。
      // console.log("complete");
    },
    fileSuccess(rootFile, file, response, chunk) {
      const result = JSON.parse(response);

      if (result.success && !this.skip) {
        axios
          .post("/upload/merge", {
            identifier: file.uniqueIdentifier,
            filename: file.name,
            totalChunks: chunk.offset,
            uploadedBy: this.user.id,
          })
          .then((res) => {
            if (res.data.code == 200) {
              this.unitForm.fileId = res.data.data;
            } else {
              console.log(res);
            }
          })
          .catch(function (error) {
            console.log(error);
          });
      } else {
        console.log("上传成功，不需要合并");
      }
      if (this.skip) {
        this.skip = false;
      }
    },
    filesAdded(files) {
      const allowedTypes = ["video/mp4"];
      const invalidFiles = [];

      files.forEach((file) => {
        if (!allowedTypes.includes(file.type)) {
          invalidFiles.push(file.name);
        } else {
          this.computeMD5(file);
        }
      });

      if (invalidFiles.length > 0) {
        alert(`只允许上传 MP4 文件：${invalidFiles.join(", ")}`);
        return;
      }
      this.fileUploaded = true; // 设置标志变量为 true，表示文件已上传
      // 其他处理逻辑...
    },
    computeMD5(file) {
      const fileReader = new FileReader();
      const time = new Date().getTime();
      const blobSlice =
        File.prototype.slice ||
        File.prototype.mozSlice ||
        File.prototype.webkitSlice;
      let currentChunk = 0;
      const chunkSize = 1024 * 1024;
      const chunks = Math.ceil(file.size / chunkSize);
      const spark = new SparkMD5.ArrayBuffer();
      // 文件状态设为"计算MD5"
      file.cmd5 = true; // 文件状态为“计算md5...”
      file.pause();
      loadNext();
      fileReader.onload = (e) => {
        spark.append(e.target.result);
        if (currentChunk < chunks) {
          currentChunk++;
          loadNext();
          // 实时展示MD5的计算进度
          console.log(
            `第${currentChunk}分片解析完成, 开始第${
              currentChunk + 1
            } / ${chunks}分片解析`
          );
        } else {
          const md5 = spark.end();
          console.log(
            `MD5计算完毕：${file.name} \nMD5：${md5} \n分片：${chunks} 大小:${
              file.size
            } 用时：${new Date().getTime() - time} ms`
          );
          spark.destroy(); // 释放缓存
          file.uniqueIdentifier = md5; // 将文件md5赋值给文件唯一标识
          file.cmd5 = false; // 取消计算md5状态
          file.resume(); // 开始上传
        }
      };
      fileReader.onerror = function () {
        this.error(`文件${file.name}读取出错，请检查该文件`);
        file.cancel();
      };
      function loadNext() {
        const start = currentChunk * chunkSize;
        const end =
          start + chunkSize >= file.size ? file.size : start + chunkSize;
        fileReader.readAsArrayBuffer(blobSlice.call(file.file, start, end));
      }
    },
  },
};
</script>

<style>

</style>